const app = getApp()
//引入封装的reuest请求
const {
  request
} = require('../http/request.js')
/**
 * getUserProfile
 */

const getUserInfo = () => {
  return new Promise((resolve, reject) => {
    wx.getUserProfile({
      desc: '用户登录',
      success: (res) => {
        resolve(res)
      },
      fail: (err) => {
        wx.showModal({
          content: '取消授权将会影响相关服务，您确定取消授权吗？',
          success(res) {
            if (res.confirm) {
              wx.showToast({
                title: '已取消授权',
                duration: 1500
              })
            } else if (res.cancel) {
              login()
            }
            // reject(err)
          }
        })

      }
    })
  })
}

/**
 * get 用户临时code
 */
const getUserCode = () => {
  return new Promise((resolve, reject) => {
    wx.login({
      success(res) {
        resolve(res)
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}
/* 登录 */
const login = (callback) => {

  let userInfo = getUserInfo();
  let userCode = getUserCode();
  Promise.all([userInfo, userCode])
    .then(res => {
      let param = {
        code: res[1].code,
        iv: res[0].iv,
        ency_data: res[0].encryptedData
      }

      request('api/login', "post", param, false).then(res => {
        let userInfo = res || {};
        // 将用户信息存入全局对象
        app.globalData.userInfo = userInfo
        try {
          wx.setStorageSync('userInfo', userInfo)
          console.log('全局存用户信息成功了')
        } catch (e) {
          console.log('全局存用户信息失败了')
        }
        callback && callback(userInfo);
      })
    })
}
/**
 * 单独封装微信上传图片
 * 一次只传一张
 * 上传地址是完整地址
 */
const upLoadImg = (cb) => {
  wx.chooseMedia({
    count: 1,
    mediaType: ['image'],
    sourceType: ['album', 'camera'],
    camera: 'back',
    success(res) {
      // 请求读取登录自定义状态
      let access_token = '';
      try {
        var userInfo = wx.getStorageSync('userInfo')
        if (userInfo) {
          access_token = userInfo.access_token
        }
        // console.log(access_token, 'request userInfo')
      } catch (e) {
        console.log('request.js中读取用户信息失败');
      }
      // console.log(res.tempFiles[0].tempFilePath,'filepath')
      wx.showLoading({
        title: '上传中',
        mask: true,
      })
      wx.uploadFile({
        filePath: res.tempFiles[0].tempFilePath,
        name: 'file',
        header: {
          'content-type': 'application/json; charset=utf-8',
          'token': access_token
        },
        url: 'https://cebei-api.nmhywl.cn/api/upload-image',
        success(res) {
          wx.hideLoading();
          let result = JSON.parse(res.data),
            imgPath = '';
          console.log()
          if (result.code == 0) {
            cb && cb(result.data.path);
          } else {
            wx.showToast({
              title: result.message,
              icon:'none',
              duration: 1500
            })
          }
          // return  
          // console.log()
        },
        fail(error) {
          wx.showToast({
            title: error,
            icon:'none',
          })
        }
      })
    }
  })
}
const getNewUserInfo = () => {
  return request('api/home', 'GET', {}, false);
}

/**
 * 通用充值
 */
const onPay = (url, method, params) => {
  return request(url, method, params, false);
}

/**
 * 获取直播间登录签名
 * 
 */
const getUserSig = () => {
  return request('api/live-room-sig','GET',{})
}

//基于业务封装的接口
module.exports = {
  login,
  upLoadImg,
  getNewUserInfo,
  onPay,
  getUserSig,
}